package com.merck.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {
    //创建Properties文件对象
    private static Properties prop = new Properties();
    //创建ThreadLocal线程锁
    private static ThreadLocal<Connection> treadLocal = new ThreadLocal<Connection>();

    static {
        //TWR语法创建Properties文件输入流
        //JDBCUtils.class.getClassLoader().getResourceAsStream("JDBC.properties")通过类加载器获取文件完全路径
        try (InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties")){
            //加载Properties文件
            prop.load(in);
            //加载数据库驱动
            Class.forName(prop.getProperty("jdbc.driver"));
        } catch (IOException e) {
            throw new RuntimeException("未读取到数据库配置" + e.getMessage());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 获取Connection对象的方法
     * @return  Connection对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        //获取与此线程绑定的Connection
        Connection conn = treadLocal.get();
        //如果不为空返回
        if(null != conn) {
            return conn;
        }
        //如果为空创建新的
        conn = DriverManager.getConnection(
                prop.getProperty("jdbc.url"), prop.getProperty("jdbc.username"), prop.getProperty("jdbc.password"));
        //把创建的线程绑定到线程
        treadLocal.set(conn);
        return conn;
    }

    /**
     * 关闭Connection
     * @throws SQLException
     */
    public static void close() throws SQLException {
        Connection conn = treadLocal.get();
        if(null != conn) {
            conn.close();
            //从线程绑定中移除
            treadLocal.remove();
        }
    }

}
